package com.chemical.search.view.manage;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.chemical.search.view.BaseController;

/**
 *@className:DBOperateController.java
 *@classDescription:
 *@author:MChen
 *@createTime:2012-7-9
 */
@Controller
@RequestMapping("/manage/database")
public class DBOperateController{
	
	private static String dbName="chemical_structures_db";  
    private static String _username = "root";  
    private static String _password = "123";  
    private static String _host = "localhost";  
    private static String _port="3306";
	 /** 
     * 备份数据库 
     * @param targetName 要备份的对象名：只能为表名和数据库名称 
     * @return 成功:TRUE 失败:FALSE 
     * 备份表直接备份在指定文件夹，备份库则按日期备份到指定的文件夹 
     * 
     */  
    @RequestMapping(value="backup")
    public static void backup(HttpServletResponse response){  
        File file = new File("");
        String backFilePath = null;  
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");  
        String backDirString = file.getAbsolutePath()+File.separator+"databaseup"+File.separator;//默认备份库  
          
        try {  
           //备份库  
                backFilePath =backDirString+dbName+"_"+sdf.format(new Date())+".sql";//要备份的文件  
                File backDir = new File(backDirString);  
                if(!backDir.exists()){//存放库的文件夹不存在  
                    backDir.mkdir();  
                }  
            //判断要备份的文件是否已存在  
            File backFile = new File(backFilePath);  
            if(backFile.exists()){  
                backFile.delete();  
            }  
            Runtime runt = Runtime.getRuntime();  
            String command =  "mysqldump -uroot -p123 --set-charset=utf8 "+dbName;
            //Process proc = runt.exec("D:/myec6_tomcat/webapps/cms/dbtools/mysqldumpwin.exe -h 127.0.0.1 -P3306   -uroot -p123 --result-file=F:/tables/menuinfo.sql --default-character-set=gbk bizoss_cms menuinfo");  
//            Process proc = runt.exec(getBackupShellString(targetName));  
            Process proc = runt.exec(command);  
            InputStream in = proc.getInputStream();// 控制台的输出信息作为输入流
            InputStreamReader xx = new InputStreamReader(in, "utf8");// 设置输出流编码为utf8。这里必须是utf8，否则从流中读入的是乱码
            String inStr;
            StringBuffer sb = new StringBuffer("");
            String outStr;
            // 组合控制台输出信息字符串
            BufferedReader br = new BufferedReader(xx);
            while ((inStr = br.readLine()) != null) {
                sb.append(inStr + "\r\n");
            }
            outStr = sb.toString();
            // 要用来做导入用的sql目标文件：
            FileOutputStream fout = new FileOutputStream(backFilePath);
            OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");
            writer.write(outStr);
            // 注：这里如果用缓冲方式写入文件的话，会导致中文乱码，用flush()方法则可以避免
            writer.flush();
            // 别忘记关闭输入输出流
            in.close();
            xx.close();
            br.close();
            writer.close();
            fout.close();
            int tag = proc.waitFor();//等待进程终止  
            if(tag==0){  
            	response.setContentType("text/html; charset=utf-8");
    			PrintWriter out = null;
    			try {
    				out = response.getWriter();
    				// 输出业务层返回的json
    				out.print("<script>alert('数据库备份成功');</script>");
    				out.flush();
    				out.close();
//    				response.sendRedirect(request.getContextPath()+"/manage/chem/add.do");
//    				request.getRequestDispatcher("/manage/chem/add.do").forward(request, response);
    			} catch (Exception e) {
    				e.printStackTrace();
    			} finally {
    				if (null != out) {
    					out.close();
    				}
    			}
            }else{  
            	System.out.println(" Output error! ");
            }  
        } catch (Exception e) {  
        }  
          
    }
    
    /** 
     * 根据路径生成恢复数据库的Shell字符串 
     * @param targetName targetName 要还原的对象名：只能为表名和数据库名称 
     * @return 恢复数据时实际执行的shell 
     */  
    private String getBackupShellString(String targetName) {
    	 String basepath=Thread.currentThread().getContextClassLoader().getResource("").toString();  
         String database_tools_path=basepath.substring(6, basepath.length()-4)+"dbtools/";//备份工具路径  
         String backFile = "";//已备份的文件  
         if(targetName.indexOf(this.dbName) == -1){//还原表  
             backFile = "f:/tables/"+targetName+".sql";  
         }else{//还原库  
                 backFile ="f:/database/"+targetName;  
         }  
         String OSType = System.getProperty("os.name");  
         String shellStr = "";  
         if(OSType.indexOf("Windows")!=-1){  
             shellStr = database_tools_path+"mysqlwin.exe -h "+this._host+" -P"+this._port+"   -u"+this._username+" -p"+  
             this._password+" --default-character-set=gbk "+this.dbName +" < "+backFile;  
         }else{  
             shellStr = database_tools_path+"mysql -h "+this._host+" -P"+this._port+"   -u"+this._username+" -p"+  
             this._password+"   --default-character-set=gbk "+this.dbName+" < "+backFile;  
         }  
         return shellStr;  
	}
    
    public static void main(String[] args) {  
        DBOperateController db=new DBOperateController();  
       // System.out.println(db.selAllTableInfo("libraryv1"));  
//        System.out.println(db.selTableStructure("bookinfo"));  
        // System.out.println(System.getProperty("os.name"));  
        //System.out.println(db.restore("t"));  
//        backup("chemical_structures_db");
//        backup();
//        load();
      }
    
    /**
      * 导入
      * 导入的时候需要数据库已经建好。
      */
        public static void load() {
            try {
                String fPath = "e:/demo.sql";
                Runtime rt = Runtime.getRuntime();
                // 调用 mysql 的 cmd:
            //    rt.exec("create database demo");
                Process child = rt.exec("mysql -uroot -proot test1");
                OutputStream out = child.getOutputStream();// 控制台的输入信息作为输出流
                String inStr;
                StringBuffer sb = new StringBuffer("");
                String outStr;
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        new FileInputStream(fPath), "utf8"));
                while ((inStr = br.readLine()) != null) {
                    sb.append(inStr + "\r\n");
                }
                outStr = sb.toString();
                OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
                writer.write(outStr);
                // 注：这里如果用缓冲方式写入文件的话，会导致中文乱码，用flush()方法则可以避免
                writer.flush();
                // 别忘记关闭输入输出流
                out.close();
                br.close();
                writer.close();
                System.out.println("/* Load OK! */");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

}
